package com.example.controller;

import com.example.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    //文件上传与下载统一处理
     @Value("${reggie.path}")
    private String basepath;
    @PostMapping("/upload")
    public R<String> uploadimage(MultipartFile file) throws IOException {
        String end=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        System.out.println(file.getName());
        System.out.println(end);
        String s= UUID.randomUUID().toString();
        String filename=s+end;
        File newfile=new File(basepath);
        if(!newfile.exists()){
            newfile.mkdir();
        }
        file.transferTo(new File(basepath+filename));
        return R.success(filename);
    }
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            FileInputStream fileInputStream=new FileInputStream(new File(basepath+name));
            ServletOutputStream outputStream = response.getOutputStream();
            int len=0;
            response.setContentType("image/jpeg");
            byte[]bytes=new byte[1024];
            while((len=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();
        } catch (IOException e) {

        }

    }
}
